package org.example;
import java.io.*;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;

public class CacheManager {
    private final String cacheDir;
    private final Map<String, Long> expiryMap;

    public CacheManager(String cacheDir) {
        this.cacheDir = cacheDir;
        this.expiryMap = new HashMap<>();
        File dir = new File(cacheDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public void saveToCache(String key, String value, long ttl) throws IOException {
        String filePath = cacheDir + File.separator + key;
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(value);
        }
        expiryMap.put(key, System.currentTimeMillis() + ttl * 1000);
    }

    public String getFromCache(String key) throws IOException {
        if (isExpired(key)) {
            return null;
        }

        String filePath = cacheDir + File.separator + key;
        if (!Files.exists(Paths.get(filePath))) {
            return null;
        }

        return new String(Files.readAllBytes(Paths.get(filePath)));
    }

    private boolean isExpired(String key) {
        Long expiryTime = expiryMap.get(key);
        if (expiryTime == null) {
            return true;
        }

        if (System.currentTimeMillis() > expiryTime) {
            expiryMap.remove(key);
            try {
                Files.deleteIfExists(Paths.get(cacheDir + File.separator + key));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }
}
